﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using HYView;

namespace YJKStairs.AddSigns
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class TestCommandTwo : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIApplication application = commandData.Application;
			Application application2 = application.Application;
			UIDocument activeUIDocument = application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			CmdViewType types = CmdViewType.FloorPlan;
			if (SwitchView.SetUsableView(types, commandData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				return Autodesk.Revit.UI.Result.Failed;
			}
			List<Element> list = new List<Element>();
			List<Transform> list2 = new List<Transform>();
			string str = "请框选所需扶梯";
			string str2 = string.Empty;
			ObjectType objectType;
			ISelectionFilter aselectionFilter = this.getASelectionFilter(application, out objectType, false);
            if (1 == (int)objectType)
			{
				str2 = "(主文档模式)";
			}
            else if (5 == (int)objectType)
			{
				str2 = "（链接文档模式)";
			}
			List<Reference> list3 = new List<Reference>();
			try
			{
				list3 = activeUIDocument.Selection.PickObjects(objectType, aselectionFilter, str + str2).ToList<Reference>();
				if (list3.Count == 0 && aselectionFilter is StairSingleLinkFileSelectionFilter)
				{
					YJKMessageBox.Show("在链接文档中没有框选到扶梯，请在主文档中尝试框选");
					aselectionFilter = this.getASelectionFilter(application, out objectType, true);
					list3 = activeUIDocument.Selection.PickObjects(objectType, aselectionFilter, "请框选所需扶梯(主文档模式)").ToList<Reference>();
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				return Autodesk.Revit.UI.Result.Succeeded;
			}
			string appRootPath = Utility.GetAppRootPath();
			string versionNumber = application.Application.VersionNumber;
			StaticRescours.SignFamilyPath = appRootPath + "\\FamilyLib\\Family\\" + versionNumber + "\\StairSign\\";
			StaticRescours.OutPutPath = Path.GetTempPath();
			AddSignManger addSignManger = new AddSignManger(document);
			List<int> list4 = new List<int>();
			List<int> list5 = new List<int>();
			if (5 == (int)objectType)
			{
				using (List<Reference>.Enumerator enumerator = list3.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						Reference reference = enumerator.Current;
						if (!Utility.IfRefenceHasAdded(ref list4, ref list5, reference))
						{
							RevitLinkInstance revitLinkInstance = document.GetElement(reference.ElementId) as RevitLinkInstance;
							Document linkDocument = revitLinkInstance.GetLinkDocument();
							list.Add(linkDocument.GetElement(reference.LinkedElementId));
							list2.Add(revitLinkInstance.GetTotalTransform());
						}
					}
					goto IL_205;
				}
			}
			foreach (Reference reference2 in list3)
			{
				if (!Utility.IfRefenceHasAdded(ref list4, ref list5, reference2))
				{
					list.Add(document.GetElement(reference2.ElementId));
					list2.Add(null);
				}
			}
			IL_205:
			int num = 0;
			int count = list.Count;
			int num2 = 0;
			for (int i = 0; i < count; i++)
			{
				if (addSignManger.AddOneSign(list[i] as FamilyInstance, ref num2, list2[i]))
				{
					num++;
				}
			}
			string str3 = string.Empty;
			if (num2 > 0)
			{
				str3 = string.Format("\r其中共有{0}个位于顶层，无法创建扶梯图例，请切换至次顶层选择", num2);
			}
			addSignManger.DeletTempFiles();
			YJKMessageBox.Show(string.Format("完成，共成功生成 {0}/{1}。" + str3, num, list.Count));
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private ISelectionFilter getASelectionFilter(UIApplication ui_app, out ObjectType objectType, bool ifthisDocument = false)
		{
			Application application = ui_app.Application;
			Document document = ui_app.ActiveUIDocument.Document;
			LevelFinder levelFinder = LevelFinder.GetLevelFinder(document);
			Level genLevel = document.ActiveView.GenLevel;
			Level topLevel = levelFinder.GetTopLevel(genLevel.Elevation);
			ISelectionFilter selectionFilter;
			if (ifthisDocument)
			{
				selectionFilter = new StairSingleSelectionFilter();
                objectType = (ObjectType)1;
			}
			else
			{
				int num = 0;
				IEnumerator enumerator = application.Documents.GetEnumerator();
				{
					while (enumerator.MoveNext())
					{
						if (((Document)enumerator.Current).IsLinked)
						{
							num++;
						}
					}
				}
				if (num == 0)
				{
					selectionFilter = new StairSingleSelectionFilter();
                    objectType = (ObjectType)1;
				}
				else
				{
					selectionFilter = new StairSingleLinkFileSelectionFilter();
                    objectType = (ObjectType)5;
				}
			}
			(selectionFilter as ISetNowLevel).SetNowLevel(genLevel);
			if (selectionFilter is StairSingleLinkFileSelectionFilter)
			{
				(selectionFilter as StairSingleLinkFileSelectionFilter).SetTopLevel(topLevel);
				(selectionFilter as StairSingleLinkFileSelectionFilter).SetDocument(document);
			}
			return selectionFilter;
		}
	}
}
